package sostats.core.query;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import sostats.core.base.StatisticalContext;

public class SqlContext {
	private final StringBuilder sql;
	public SqlContext(){
		this.sql  = new StringBuilder();
	}
	public void append(SqlContext subContext){
		this.sql.append("(").append(subContext.buildSql()).append("\n)");
	}
	public void append(String clause){
		this.sql.append(clause).append("\n");
	}
	public String buildSql(){
		return sql.toString();
	}
	public Select select(){
		return new Select(this);
	}
	public ResultSet execute(Connection connection) throws SQLException{
		PreparedStatement ps = connection.prepareStatement(this.buildSql().replaceAll(StatisticalContext.CONNECTOR, "."));
		return ps.executeQuery();
	}
}
